import { Card, Row, Col, DatePicker, Table, Form, Button, Modal, Upload, Icon, message } from 'antd';
import React, { Component }from 'react';

import *as XLSX from 'xlsx';
import styles from '../style.less';
import IconFont from '@/components/Icon'


class ImportButton extends Component {
    state = {
        showModal: false,
        columns:[
            {
                title: '企业名称',
                dataIndex: 'name',
            },{
                title: '所在街道',
                dataIndex: 'street',
            },{
                title: '行业类型',
                dataIndex: 'industry',
            },{
                title: '产品数量',
                dataIndex: 'numble',
            },{
                title: '法人代表',
                dataIndex: 'owner',
            },{
                title: '联系电话',
                dataIndex: 'phone',
            },
        ],
        data:[
            {
            "name": 'hahahahahha哈哈啊',
            age: 13,
            address: '我玩牛逼i'
            },
            {
            "name": 'hahahahahha哈哈啊',
            age: 13,
            address: '我玩牛逼i'
            },
            {
            "name": 'hahahahahha哈哈啊',
            age: 13,
            address: '我玩牛逼i'
            },

        ],
        fileList:[],
        importExcle: []
    }

    componentDidMount = () => {

    }
    

    btnHandleClick = () => {
        console.log('点击导入企业')
        this.setState({
            showModal: true
        })
    }

    onCancel = () => {
        this.setState({ showModal: false })
    }

    exportCompanyOK = () => {
        const { importConfirm } = this.props
        if (this.state.importExcle.length === 0) {
            this.setState({
                showModal: false
            })
            return;
        }
        importConfirm(this.state.importExcle)
        
    }

    formatTitleOrFileld = (a, b) => {
        const entozh = {};
        this.state.columns.forEach(item => {
            entozh[item[a]] = item[b]
        })
        return entozh;
    }

    handleImpotedJson = (array, file) => {
       
        const header = array[0];
        const entozh = this.formatTitleOrFileld('title', 'dataIndex');
        const firstRow = header.map(item => entozh[item]);

        const newArray = [...array];

        newArray.splice(0, 1);

        const json = newArray.map((item, index) => {
            const newitem = {};
            item.forEach((im, i) => {
                const newKey = firstRow[i] || i;
                newitem[newKey] = im
            })
            return newitem;
        });

        const formatData = json.map(item => ({
            name: item.name,
            age: item.age,
            address: item.address,
        }))
        console.log(this.state.fileList)
        this.setState({ 
            data: formatData, 
            fileList: [file],
            importExcle: json
        });
        console.log(this.state.fileList)

        return formatData;
    }
    
    render () {
        const { columns, data, fileList }=this.state;

        const uploadProps={
            onRemove: file => {
                this.setState(state => ({
                    // eslint-disable-next-line react/no-unused-state
                    data:[],
                    // eslint-disable-next-line react/no-unused-state
                    fileList:[]
                }));
            },
            accept: ".xls,.xlsx,application/vnd.ms-excel",
            beforeUpload: file => {
                this.setState({
                    fileList: []
                })
                // eslint-disable-next-line no-underscore-dangle
                const f = file;
                const reader = new FileReader();
                reader.onload = e =>  {

                    const datas = e.target.result;

                    const workbook = XLSX.read(datas, {
                        type: 'binary'
                    }); // 尝试解析datas
 
                    // eslint-disable-next-line @typescript-eslint/camelcase
                    const first_worksheet = workbook.Sheets[workbook.SheetNames[0]];// 是工作簿中的工作表的有序列表

                    const jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });// 将工作簿对象转换为JSON对象数组

                    this.handleImpotedJson(jsonArr, file)
                };
                reader.readAsBinaryString(f);
                return false;
            },
            onChange(info) {
                if (info.file.status !== 'uploading') {
                //   console.log(info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    // message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                //   message.error(`${info.file.name} file upload failed.`);
                }
            },
            // fileList,
        };

        return (
            <>
                <Button
                    className={styles.downCompany}
                    icon="arrow-down" 
                    type="primary" 
                    onClick={this.btnHandleClick}
                >
                    导入企业
                </Button>

                <Modal
                    title="导入详情"
                    visible={this.state.showModal}
                    onOk={this.exportCompanyOK}
                    onCancel={this.onCancel}
                    okText="导入"
                >   
                    <h4 style={{padding: '10px 0'}}>
                        导入文件
                    </h4>
                    {
                        this.state.fileList.length ?  
                        (
                            <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom:'20px'}}>
                                <div style={{display: 'flex', alignItems: 'center' }}>
                                    <IconFont type="icon-excel" style={{width:'40px',height: '40px', fontSize: '40px', marginRight:'10px'}}/>
                                    <span> {this.state.fileList[0].name} </span>
                                </div>
                                <Upload {...uploadProps}>
                                    <a style={{float:'right'}}>重新上传</a>
                                </Upload>
                            </div>
                        )
                        : 
                        (
                            <Upload {...uploadProps}>
                                <Button>
                                    <Icon type="upload" /> 选择文件
                                </Button>
                            </Upload>
                        )
                    }
                    
                </Modal>
            </>
        )
    }
}


export default ImportButton
